package net.lainiao.leetcode.LeetCode;

import java.util.HashMap;

public class LeetCode128 {
    //求最长连续序列的长度
    public static void main(String[] args) {
        int[] nums1={100, 4, 200, 1, 3, 2};
        int res1=GetLongestConsecutiveSequenceLength(nums1);
        System.out.println(res1==4);
        int[] nums2={3,1,4,1,5,9,2,6,5};
        int res2=GetLongestConsecutiveSequenceLength(nums2);
        System.out.println(res2==6);
    }

    private static int GetLongestConsecutiveSequenceLength(int[] nums) {
        HashMap hashMap=new HashMap();
        for (int i = 0; i <nums.length ; i++) {
            hashMap.put(nums[i],1);
        }
        int max=0;
        for (int i = 0; i <nums.length ; i++) {
            if(hashMap.containsKey(nums[i])){
                int len=1;
                int tem=nums[i]+1;
                while (hashMap.containsKey(tem)){
                    hashMap.remove(tem);
                    len++;
                    tem++;
                }
                tem=nums[i]-1;
                while (hashMap.containsKey(tem)){
                    hashMap.remove(tem);
                    len++;
                    tem--;
                }
                if(len>max){
                    max=len;
                }
            }
        }
        return max;
    }
}
